package com.hongye.house.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.hongye.house.config.HongYeESConfig;
import com.hongye.house.entity.*;
import com.hongye.house.service.*;
import com.hongye.house.vo.SaleHomeVo;
import com.hongye.house.vo.SaleQueryVo;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hongye.common.utils.PageUtils;
import com.hongye.common.utils.Query;

import com.hongye.house.dao.SaleHomeDao;


@Service("saleHomeService")
public class SaleHomeServiceImpl extends ServiceImpl<SaleHomeDao, SaleHomeEntity> implements SaleHomeService {


    @SuppressWarnings("all")
    @Autowired
    private RestHighLevelClient client;


    @Autowired
    SaleHomeService saleHomeService;

    //楼盘表
    @Autowired
    private PropertiesSaleHomeService propertiesSaleHomeService;

    //地区表
    @Autowired
    private CityHomeService cityHomeService;

    //房屋类型表
    @Autowired
    private TypeHomeService typeHomeService;

    //房屋朝向表
    @Autowired
    private OrientationHomeService orientationHomeService;

    //房屋封面表
    @Autowired
    private CoverImgService coverImgService;

    //房屋户型
    @Autowired
    private HouseImgService houseImgService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<SaleHomeEntity> homeEntityQueryWrapper = new QueryWrapper<SaleHomeEntity>().orderByDesc("house_createtime");
        IPage<SaleHomeEntity> page = this.page(
                new Query<SaleHomeEntity>().getPage(params),
                homeEntityQueryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<SaleHomeEntity> salelist(Integer houseagent) {
        return baseMapper.selectList(new QueryWrapper<SaleHomeEntity>().eq("house_agent",houseagent));
    }

    @Override
    public void esoldinsert() {
        List<SaleHomeEntity> list = baseMapper.selectList(new QueryWrapper<SaleHomeEntity>().eq("house_secondhand",1));
        //批量请求
        BulkRequest request = new BulkRequest();
        list.stream().forEach( a ->{
            //创建索引
            IndexRequest indexRequest = new IndexRequest("saleoldhouseshop").id(a.getHouseId().toString());
            //因为我的a是个对象 循环查每一条数据 批量添加
            //es里添加规定的要string类型所以要把a 转成string类型进行操作
            String s = JSONObject.toJSONString(a);

            IndexRequest source = indexRequest.source(s, XContentType.JSON);
            //添加
            request.add(indexRequest,source);
        });
        try {
            client.bulk(request, HongYeESConfig.COMMON_OPTIONS);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void esnewinsert() {
        List<SaleHomeEntity> list = baseMapper.selectList(new QueryWrapper<SaleHomeEntity>().eq("house_secondhand",0));
        //批量请求
        BulkRequest request = new BulkRequest();
        list.stream().forEach( a ->{
            //创建索引
            IndexRequest indexRequest = new IndexRequest("salenewhouseshop").id(a.getHouseId().toString());
            //因为我的a是个对象 循环查每一条数据 批量添加
            //es里添加规定的要string类型所以要把a 转成string类型进行操作
            String s = JSONObject.toJSONString(a);

            IndexRequest source = indexRequest.source(s, XContentType.JSON);
            //添加
            request.add(indexRequest,source);
        });
        try {
            client.bulk(request, HongYeESConfig.COMMON_OPTIONS);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Integer secondhandhousing() {
        return baseMapper.selectCount(new QueryWrapper<SaleHomeEntity>().eq("house_secondhand",1));
    }

    @Override
    public Integer numberofnewhouses() {
        return baseMapper.selectCount(new QueryWrapper<SaleHomeEntity>().eq("house_secondhand",0));
    }

    @Override
    public List<SaleHomeEntity> esnewsearch(SaleQueryVo vo) throws IOException {
        SearchRequest searchRequest = new SearchRequest("salenewhouseshop");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        if (vo.getHousePricemax() != null && vo.getHousePricemin() != null) {
            boolQueryBuilder.must(QueryBuilders.rangeQuery("housePrice").gte(vo.getHousePricemax()).lte(vo.getHousePricemin()));
        }
        searchSourceBuilder.query(boolQueryBuilder);
        searchRequest.source(searchSourceBuilder);

        SearchResponse searchResponse = client.search(searchRequest, HongYeESConfig.COMMON_OPTIONS);
        SearchHits hits = searchResponse.getHits();
        TotalHits totalHits = hits.getTotalHits();
// the total number of hits, must be interpreted in the context of totalHits.relation
        Long numHits = totalHits.value;
        SearchHit[] searchHits = hits.getHits();
        List<SaleHomeEntity> list1 = Arrays.stream(searchHits).map(b -> {
            SaleHomeEntity saleHomeEntity = JSONObject.parseObject(b.getSourceAsString(), SaleHomeEntity.class);
            return saleHomeEntity;
        }).collect(Collectors.toList());

        return list1;
    }

    @Override
    public List<SaleHomeEntity> esoldsearch(SaleQueryVo vo) throws IOException {
        SearchRequest searchRequest = new SearchRequest("saleoldhouseshop");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        if (vo.getHousePricemax() != null && vo.getHousePricemin() != null) {
            boolQueryBuilder.must(QueryBuilders.rangeQuery("housePrice").gte(vo.getHousePricemax()).lte(vo.getHousePricemin()));
        }
        searchSourceBuilder.query(boolQueryBuilder);
        searchRequest.source(searchSourceBuilder);

        SearchResponse searchResponse = client.search(searchRequest, HongYeESConfig.COMMON_OPTIONS);
        SearchHits hits = searchResponse.getHits();
        TotalHits totalHits = hits.getTotalHits();
// the total number of hits, must be interpreted in the context of totalHits.relation
        Long numHits = totalHits.value;
        SearchHit[] searchHits = hits.getHits();
        List<SaleHomeEntity> list1 = Arrays.stream(searchHits).map(b -> {
            SaleHomeEntity saleHomeEntity = JSONObject.parseObject(b.getSourceAsString(), SaleHomeEntity.class);
            return saleHomeEntity;
        }).collect(Collectors.toList());

        return list1;
    }



    @Override
    public List<SaleHomeVo> getsalelist() {

        ArrayList<SaleHomeVo> saleHomeVos = new ArrayList<>();
        //房源
        List<SaleHomeEntity> saleHomeEntities = baseMapper.selectList(null);
        for (SaleHomeEntity saleHomeEntity : saleHomeEntities) {
            SaleHomeVo saleHomeVo = new SaleHomeVo();
            BeanUtils.copyProperties(saleHomeEntity,saleHomeVo);
            saleHomeVos.add(saleHomeVo);
        }
        //地区表
        List<CityHomeEntity> cityHome = cityHomeService.list();
        //楼盘表
        List<PropertiesSaleHomeEntity> properties = propertiesSaleHomeService.list();
        //房屋类型表
        List<TypeHomeEntity> typeHome = typeHomeService.list();
        //房屋朝向表
        List<OrientationHomeEntity> orientation = orientationHomeService.list();
        //房屋封面表
        List<CoverImgEntity> coverImg = coverImgService.list();
        //房屋户型
        List<HouseImgEntity> Shape = houseImgService.list();


        saleHomeVos.stream().forEach(a->{
            //地区赋值
            if (a.getHousePid()!=null){
                for (CityHomeEntity cityHomeEntity : cityHome) {
                    if (a.getHousePid().equals(cityHomeEntity.getPid())){
                        a.setPname(cityHomeEntity.getName());
                    }
                    if (a.getHouseCid()==cityHomeEntity.getPid()){
                        a.setCname(cityHomeEntity.getName());
                    }
                    if (a.getHouseYid()==cityHomeEntity.getPid()){
                        a.setYname(cityHomeEntity.getName());
                    }
                }
            }


            //楼盘表赋值
            if (a.getPropertiesId()!=null) {
                for (PropertiesSaleHomeEntity property : properties) {
                    if (a.getPropertiesId().equals(property.getPropertiesSaleId())) {
                        a.setPropertiesSaleName(property.getPropertiesSaleName());
                        a.setPropertiesSaleAddress(property.getPropertiesSaleAddress());
                    }
                }
            }
            //房屋类型赋值
            if (a.getHouseType()!=null) {
                for (TypeHomeEntity typeHomeEntity : typeHome) {
                    if (a.getHouseType().equals(typeHomeEntity.getTypeId())) {
                        a.setTypeName(typeHomeEntity.getTypeName());
                    }
                }
            }
            //房屋朝向赋值
            if (a.getHouseOrientation()!=null) {
                for (OrientationHomeEntity orientationHomeEntity : orientation) {
                    if (a.getHouseOrientation().equals(orientationHomeEntity.getOrientationId())) {
                        a.setOrientationName(orientationHomeEntity.getOrientationName());
                    }
                }
            }

            //房屋户型
            if (a.getHouseShape()!=null){
                for (HouseImgEntity houseImgEntity : Shape) {
                    if (a.getHouseShape().equals(houseImgEntity.getHomeId())){
                        a.setHouseShapeImg(houseImgEntity.getHomeShapeImg());
                        a.setHouseShapeName(houseImgEntity.getHouseShapeName());
                    }
                }
            }


            //房屋封面赋值
            if (a.getHouseId()!=null) {
                for (CoverImgEntity coverImgEntity : coverImg) {
                    if (a.getHouseId().equals(coverImgEntity.getHouseId())) {
                        a.setHouseImg(coverImgEntity.getCoverImg());
                    }
                }
            }
        });
        return saleHomeVos;
    }

    @Override
    public void eshouseadd() {
        List<SaleHomeVo> getsalelist = saleHomeService.getsalelist();
        //批量请求
        BulkRequest request = new BulkRequest();
        getsalelist.stream().forEach( a ->{
            //创建索引
            IndexRequest indexRequest = new IndexRequest("houseshop").id(a.getHouseId().toString());
            //因为我的a是个对象 循环查每一条数据 批量添加
            //es里添加规定的要string类型所以要把a 转成string类型进行操作
            String s = JSONObject.toJSONString(a);

            IndexRequest source = indexRequest.source(s, XContentType.JSON);
            //添加
            request.add(indexRequest,source);
        });
        try {
            client.bulk(request, HongYeESConfig.COMMON_OPTIONS);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<SaleHomeVo> eshousesearch(SaleQueryVo vo) throws IOException {
        SearchRequest searchRequest = new SearchRequest("houseshop");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        if (vo.getHousePricemax() != null && vo.getHousePricemin() != null) {
            boolQueryBuilder.must(QueryBuilders.rangeQuery("housePrice").gte(vo.getHousePricemax()).lte(vo.getHousePricemin()));
        }
        if (vo.getOrientationName()!=null){
            boolQueryBuilder.must(QueryBuilders.termQuery("orientationName", vo.getOrientationName()));
        }
        if (vo.getHouseSecondhand()!=null){
            boolQueryBuilder.must(QueryBuilders.termQuery("houseSecondhand", vo.getHouseSecondhand()));
        }
        if (vo.getHouseShapeName()!=null){
            boolQueryBuilder.must(QueryBuilders.termQuery("houseShapeName", vo.getHouseShapeName()));
        }
        searchSourceBuilder.query(boolQueryBuilder);
        searchRequest.source(searchSourceBuilder);

        SearchResponse searchResponse = client.search(searchRequest, HongYeESConfig.COMMON_OPTIONS);
        SearchHits hits = searchResponse.getHits();
        TotalHits totalHits = hits.getTotalHits();
// the total number of hits, must be interpreted in the context of totalHits.relation
        Long numHits = totalHits.value;
        SearchHit[] searchHits = hits.getHits();
        List<SaleHomeVo> list1 = Arrays.stream(searchHits).map(b -> {
            SaleHomeVo saleHomeVo = JSONObject.parseObject(b.getSourceAsString(), SaleHomeVo.class);
            return saleHomeVo;
        }).collect(Collectors.toList());

        return list1;
    }


}